<template>
  <div class="qr-scanner-container">
    <div class="scanner-wrapper">
      <!-- 摄像头视频流 -->
      <video
        ref="videoRef"
        class="video-preview"
        autoplay
        playsinline
      ></video>
      
      <!-- 扫描框 -->
      <div class="scan-frame">
        <div class="scan-line"></div>
        <div class="corner corner-tl"></div>
        <div class="corner corner-tr"></div>
        <div class="corner corner-bl"></div>
        <div class="corner corner-br"></div>
      </div>
      
      <!-- 扫描状态提示 -->
      <div v-if="isScanning" class="scanning-status">
        <span class="status-text">扫描中...</span>
      </div>
      
      <!-- 扫描结果提示 -->
      <div v-if="scanResult" class="scan-result" :class="scanResult.success ? 'success' : 'error'">
        <span class="result-text">{{ scanResult.message }}</span>
      </div>
    </div>
    
    <!-- 控制按钮 -->
    <div class="controls">
      <button
        class="control-btn"
        :disabled="isScanning"
        @click="toggleScanner"
      >
        {{ isActive ? '关闭扫描' : '开始扫描' }}
      </button>
      <button
        class="control-btn"
        :disabled="!isActive"
        @click="switchCamera"
      >
        切换摄像头
      </button>
    </div>
    
    <!-- 错误提示 -->
    <div v-if="error" class="error-message">
      {{ error }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick } from 'vue';
import jsQR from 'jsqr';

// 定义组件的属性和事件
const props = defineProps<{
  /** 是否自动开始扫描 */
  autoStart?: boolean;
  /** 扫描成功后是否自动停止 */
  stopOnSuccess?: boolean;
}>();

const emit = defineEmits<{
  /** 扫描成功事件 */
  scanSuccess: [data: string];
  /** 扫描失败事件 */
  scanError: [error: Error];
  /** 扫描状态变化事件 */
  statusChange: [active: boolean];
}>();

// 组件内部状态
const videoRef = ref<HTMLVideoElement | null>(null);
const canvasRef = ref<HTMLCanvasElement>();
const isActive = ref(false);
const isScanning = ref(false);
const error = ref<string>('');
const scanResult = ref<{ success: boolean; message: string } | null>(null);
const stream = ref<MediaStream | null>(null);
const requestId = ref<number>();
const currentCamera = ref<'user' | 'environment'>('environment');

// 创建canvas元素
const createCanvas = () => {
  if (!canvasRef.value) {
    canvasRef.value = document.createElement('canvas');
  }
  return canvasRef.value;
};

// 开始视频流
const startVideo = async () => {
  try {
    error.value = '';
    
    // 尝试获取摄像头权限
    const constraints: MediaStreamConstraints = {
      video: {
        facingMode: currentCamera.value === 'user' ? 'user' : { exact: 'environment' },
        width: { ideal: 1920 },
        height: { ideal: 1080 },
      },
    };
    
    stream.value = await navigator.mediaDevices.getUserMedia(constraints);
    
    if (videoRef.value && stream.value) {
      videoRef.value.srcObject = stream.value;
      isActive.value = true;
      emit('statusChange', true);
      
      // 等待视频元数据加载完成后开始扫描
      await new Promise<void>((resolve) => {
        if (videoRef.value && videoRef.value.readyState >= 2) {
          resolve();
        } else {
          const onLoadedMetadata = () => {
            if (videoRef.value) {
              videoRef.value.removeEventListener('loadedmetadata', onLoadedMetadata);
              resolve();
            }
          };
          videoRef.value?.addEventListener('loadedmetadata', onLoadedMetadata);
        }
      });
      
      // 如果设置了自动开始扫描，则启动扫描
      if (props.autoStart) {
        startScan();
      }
    }
  } catch (err) {
    handleError(err as Error);
  }
};

// 停止视频流
const stopVideo = () => {
  if (stream.value) {
    stream.value.getTracks().forEach((track) => track.stop());
    stream.value = null;
  }
  
  if (videoRef.value) {
    videoRef.value.srcObject = null;
  }
  
  isActive.value = false;
  emit('statusChange', false);
};

// 开始扫描
const startScan = () => {
  if (!isActive.value || isScanning.value) return;
  
  isScanning.value = true;
  scanResult.value = null;
  
  // 开始扫描循环
  const scanLoop = () => {
    if (!isScanning.value || !videoRef.value) {
      return;
    }
    
    try {
      const canvas = createCanvas();
      const context = canvas.getContext('2d');
      
      if (!context) {
        throw new Error('无法获取Canvas上下文');
      }
      
      // 设置canvas尺寸与视频尺寸一致
      canvas.width = videoRef.value.videoWidth;
      canvas.height = videoRef.value.videoHeight;
      
      // 绘制视频帧到canvas
      context.drawImage(videoRef.value, 0, 0, canvas.width, canvas.height);
      
      // 获取图像数据
      const imageData = context.getImageData(0, 0, canvas.width, canvas.height);
      
      // 使用jsQR解码二维码
      const code = jsQR(imageData.data, imageData.width, imageData.height, {
        inversionAttempts: 'dontInvert',
      });
      
      // 如果成功解码
      if (code) {
        handleScanSuccess(code.data);
      } else {
        // 继续扫描
        requestId.value = requestAnimationFrame(scanLoop);
      }
    } catch (err) {
      handleError(err as Error);
    }
  };
  
  // 开始扫描循环
  requestId.value = requestAnimationFrame(scanLoop);
};

// 停止扫描
const stopScan = () => {
  if (requestId.value) {
    cancelAnimationFrame(requestId.value);
    requestId.value = undefined;
  }
  isScanning.value = false;
  scanResult.value = null;
};

// 处理扫描成功
const handleScanSuccess = (data: string) => {
  scanResult.value = {
    success: true,
    message: '扫描成功',
  };
  emit('scanSuccess', data);
  
  if (props.stopOnSuccess) {
    stopScan();
  } else {
    // 继续扫描
    setTimeout(() => {
      scanResult.value = null;
      if (isActive.value && isScanning.value) {
        requestId.value = requestAnimationFrame(() => {
          if (isScanning.value) startScan();
        });
      }
    }, 1000);
  }
};

// 处理扫描错误
const handleError = (err: Error) => {
  const errorMessage = err.message || '扫描失败';
  error.value = errorMessage;
  scanResult.value = {
    success: false,
    message: errorMessage,
  };
  emit('scanError', err);
  
  // 1秒后清除错误提示
  setTimeout(() => {
    scanResult.value = null;
  }, 1000);
};

// 切换扫描器状态
const toggleScanner = async () => {
  if (isActive.value) {
    stopScan();
    stopVideo();
  } else {
    await startVideo();
  }
};

// 切换摄像头
const switchCamera = async () => {
  currentCamera.value = currentCamera.value === 'user' ? 'environment' : 'user';
  
  // 停止当前视频流并重新启动
  stopScan();
  stopVideo();
  await nextTick();
  await startVideo();
  
  // 如果之前正在扫描，则重新开始扫描
  if (props.autoStart) {
    startScan();
  }
};

// 组件挂载时的初始化
onMounted(async () => {
  // 检查浏览器是否支持媒体设备API
  if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
    error.value = '您的浏览器不支持摄像头扫描功能';
    return;
  }
  
  // 如果设置了自动开始，则初始化视频流
  if (props.autoStart) {
    await startVideo();
  }
});

// 组件卸载时清理资源
onUnmounted(() => {
  stopScan();
  stopVideo();
});
</script>

<style scoped>
.qr-scanner-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  max-width: 500px;
  margin: 0 auto;
  padding: 20px;
  box-sizing: border-box;
}

.scanner-wrapper {
  position: relative;
  width: 100%;
  aspect-ratio: 4 / 3;
  margin-bottom: 20px;
  overflow: hidden;
  border-radius: 8px;
  background-color: #000;
}

.video-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.scan-frame {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80%;
  aspect-ratio: 1;
  border: 2px solid rgba(255, 255, 255, 0.6);
  box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.5);
  pointer-events: none;
}

.scan-line {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 2px;
  background: linear-gradient(90deg, transparent, #1890ff, transparent);
  animation: scanLineMove 2s linear infinite;
}

@keyframes scanLineMove {
  0% {
    top: 0;
  }
  50% {
    top: 100%;
  }
  100% {
    top: 0;
  }
}

.corner {
  position: absolute;
  width: 20px;
  height: 20px;
  border-color: #1890ff;
  border-style: solid;
}

.corner-tl {
  top: -2px;
  left: -2px;
  border-width: 2px 0 0 2px;
}

.corner-tr {
  top: -2px;
  right: -2px;
  border-width: 2px 2px 0 0;
}

.corner-bl {
  bottom: -2px;
  left: -2px;
  border-width: 0 0 2px 2px;
}

.corner-br {
  bottom: -2px;
  right: -2px;
  border-width: 0 2px 2px 0;
}

.scanning-status,
.scan-result {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 14px;
  color: #fff;
  backdrop-filter: blur(10px);
}

.scanning-status {
  background-color: rgba(0, 0, 0, 0.5);
}

.scan-result.success {
  background-color: rgba(52, 199, 89, 0.8);
}

.scan-result.error {
  background-color: rgba(255, 69, 0, 0.8);
}

.controls {
  display: flex;
  gap: 12px;
  justify-content: center;
  width: 100%;
}

.control-btn {
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s;
}

.control-btn:not(:disabled) {
  background-color: #1890ff;
  color: #fff;
}

.control-btn:not(:disabled):hover {
  background-color: #40a9ff;
}

.control-btn:disabled {
  background-color: #d9d9d9;
  color: #999;
  cursor: not-allowed;
}

.error-message {
  margin-top: 12px;
  padding: 8px 12px;
  border-radius: 4px;
  background-color: #fff1f0;
  color: #ff4d4f;
  font-size: 14px;
  line-height: 1.5;
  text-align: center;
}

/* 响应式调整 */
@media (max-width: 480px) {
  .qr-scanner-container {
    padding: 10px;
  }
  
  .scanner-wrapper {
    aspect-ratio: 1;
  }
  
  .scan-frame {
    width: 90%;
  }
  
  .controls {
    flex-direction: column;
  }
  
  .control-btn {
    width: 100%;
  }
}
</style>